package com.je.servicecomb.nacos;

import com.je.common.base.spring.SpringContextHolder;
import org.apache.servicecomb.registry.nacos.NacosSchemaStorageProvider;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.List;
import java.util.Map;

public class NacosSchemaRedisProvider implements NacosSchemaStorageProvider {

    private static final String SCHEMA_KEY = "servicecomb.schema";

    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addSchema(String serviceId, String schemaId, String content) {
        getRedisTemplate();
        stringRedisTemplate.opsForHash().put(SCHEMA_KEY + ":" + serviceId, schemaId, content);
    }

    @Override
    public void allSchemas(String serviceId, Map<String, String> schemaMap) {
        getRedisTemplate();
        stringRedisTemplate.opsForHash().putAll(SCHEMA_KEY + ":" + serviceId, schemaMap);
    }

    @Override
    public String getSchema(String serviceId, String schemaId) {
        getRedisTemplate();
        Object schema = stringRedisTemplate.opsForHash().get(SCHEMA_KEY + ":" + serviceId, schemaId);
        return schema == null ? null : schema.toString();
    }

    @Override
    public Map<String, String> getServiceSchemas(String serviceId) {
        getRedisTemplate();
        Map<Object, Object> schema = stringRedisTemplate.opsForHash().entries(SCHEMA_KEY + ":" + serviceId);
        if (schema == null) {
            return null;
        }
        Map<String, String> result = new java.util.HashMap<>(schema.size());
        for (Map.Entry<Object, Object> entry : schema.entrySet()) {
            result.put(entry.getKey().toString(), entry.getValue().toString());
        }
        return result;
    }

    @Override
    public void deleteSchema(String serviceId, String schemaId) {
        getRedisTemplate();
        stringRedisTemplate.opsForHash().delete(SCHEMA_KEY + ":" + serviceId, schemaId);
    }

    @Override
    public void deleteAllSchemas(String serviceId) {
        getRedisTemplate();
        stringRedisTemplate.delete(SCHEMA_KEY + ":" + serviceId);
    }

    @Override
    public void deleteSchema(String serviceId, List<String> schemaIdList) {
        getRedisTemplate();
        stringRedisTemplate.opsForHash().delete(SCHEMA_KEY + ":" + serviceId, schemaIdList);
    }

    private void getRedisTemplate() {
        synchronized (NacosSchemaRedisProvider.class) {
            if (stringRedisTemplate == null) {
                stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
            }
        }
    }

}
